<?php
namespace Admin\Controller;
use Think\Model;
use Vendor\Tree;

class ShopController extends ComController
{
    private $shopData = null;

    public function index()
    {
        $floorid = I('get.floorid','','intval');
        $p       = I('get.p', 1, 'intval');
        $keyword = trim(I('get.keyword',''));

        $this->getFloors($floorid);

        $m = M('shop');
        $map = array(
            'status'=>1
        );

        if (!empty($keyword)) {
            $map['name'] = array('like', "%$keyword%");
        }

        if (!empty($floorid)) {
            $map['floorid'] = $floorid;
        }

        $psize = 20;

        $list = $m->where($map)->order('floorid ASC')->page($p, $psize)->select();
        $count = $m->where($map)->count();

        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();

        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->display();
    }

    public function add()
    {
        if (!IS_POST) {
            $this->assign('guid' ,getGID());
            $this->getFloors();
            return $this->display();
        }

        $data = I('post.');
        $shopModel = M('shop');

        if (empty($data['floorid'])) {
            return $this->ajaxReturn(array('code'=>0,'msg'=>'请选择楼层'));
        }

        $guid = I('post.guid','');

        if (empty($guid)) {
            return $this->ajaxReturn(array('code'=>0,'msg'=>'参数错误！'));
        }

        $hasPic = M('Shop_imgs')->where(['guid'=>$guid])->count();

        if (empty($hasPic)) {
            return $this->ajaxReturn(array('code'=>0,'msg'=>'请上传图片'));
        }

        $m = new Model();

        try{
            $m->startTrans();
            $this->beforeSubmit();
            $shopId = $m->table("__SHOP__")->add($this->shopData);

            if (empty($shopId)) {
                throw new Exception('添加失败', -1);
            }

            $updRes = $m->table("__SHOP_IMGS__")->where(['guid'=>$guid])->data(['shop_id'=>$shopId,'status'=>1])->save();

            if (false == $updRes) {
                throw new Exception('添加商铺店铺集失败', -1);
            }

            $info['code'] = 1;
            $info['msg'] = '添加成功！';
            $m->commit();

        }catch(Exception $e){
            $m->rollback();
            $info['coce'] = 0;
            $info['msg']    = $e->getMessage();
        }

        return $this->ajaxReturn($info);
    }

    public function del($ids){
       if (empty($ids)) {
        return $this->error('参数错误！');
    }

    $res = M('shop')->where(['id'=>$ids])->data(['status'=>0])->save();

        if (!$res) {
            return $this->error('删除失败');
        }

        return $this->success('删除成功');
    }

    public function update()
    {
        $ids = I('param.ids','', 'intval');

        if (empty($ids)) {
            return $this->error('参数错误!');
            // return $this->ajaxReturn(array('status'=>0, 'msg'=>'参数错误'));
        }

        $m = M('shop');
        $where = "id='{$ids}'";

        if(!IS_POST){
            $info = $m->where($where)->find();

            if (empty($info)) {
                return $this->error('获取失败!');
            }

            $imgs = M('Shop_imgs')->where(['shop_id'=>$info['id']])->find();

            if (empty($imgs)) {
                $guid = getGID();
            }else{
                $guid = $imgs['guid'];
            }

            $this->getFloors($info['floorid']);

            $this->assign('info', $info);
            $this->assign('guid', $guid);

            return $this->display();
        }

        $guid = I('post.guid','');

        if (empty($guid)) {
            return $this->ajaxReturn(['code'=>0,'msg'=>'参数错误！']);
        }

        $this->beforeSubmit();
        $model = new Model();

        try{
            $model->startTrans();
            $res = $model->table('__SHOP__')->where($where)->data($this->shopData)->save();

            if (false === $res) {
                throw new Exception('修改失败！', -1);
            }

            $updPicRes = $model->table("__SHOP_IMGS__")
            ->where(['guid'=>$guid,'status'=>0])
            ->save(['status'=>1,'shop_id'=>$ids]);

            if (false === $updPicRes) {
                throw new Exception('修改图片失败！', -2);
            }

            $info = ['code'=>0,'msg'=>'修改成功'];

            $model->commit();
        }catch(Exception $e){
            $model->rollback();
            $info['code'] = 0;
            $info['msg'] = '修改失败！';
        }

        return $this->ajaxReturn($info);
    }

    public function getFloors($sid = 0)
    {
       $floors = M('floors')->field('id,name')->order('sort asc')->select();
       $tree = new Tree($floors);
       $str = "<option value=\$id \$selected>\$name</option>"; //生成的形式
       $floors = $tree->get_tree(0, $str, $sid);

       // print_r($floors);exit;

       $this->assign('floors', $floors);
    }

    public function floors()
    {
       $floors = M('floors')->field('id,name')->order('sort asc')->select();

       $this->assign('floors', $florrs);

       return $this->display();
    }

    private function beforeSubmit(){
        $data = I('post.');
        $this->shopData = array(
            'floorid'   => intval($data['floorid']),
            'name'      => trim($data['shopname']),
            'shopnum'   => trim($data['shopnum']),
            'tel'       => trim($data['tel']),
            'address'   => trim($data['address']),
            'starttime' => trim($data['starttime']),
            'endtime'   => trim($data['endtime']),
            'summary'   => trim($data['summary']),
            'content'   => $data['content'],
            'mainImg'   => trim($data['shopMainImg']),
            'logo'      => trim($data['logo']),
        );
    }
}
